//
//  LCMainViewController.swift
//  mggz
//
//  Created by 匀视网Mac on 2018/1/3.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SVProgressHUD
import MMDrawerController
class LCMainViewController: UIViewController {
    
    @IBOutlet weak var headerView: UIView!
    @IBOutlet weak var projectName: UILabel!
    var selectedProject : LCProjectListModel?
    lazy var itemArray : [LCProjectListModel] = [LCProjectListModel]()
    let titleArray = ["现场","民工"]
    fileprivate lazy var dropDownMenu : DropDownMenu = {
        let dropDownMenu = DropDownMenu.initDropDownMenu(size: CGSize(width: SCREEN_WIDTH*0.9, height: SCREEN_HEIGHT*0.618))
        return dropDownMenu
    }()
    fileprivate lazy var segmentView : UISegmentedControl = {
        let segmentView = UISegmentedControl(items: titleArray)
        segmentView.frame = CGRect(x: 0, y: 0, width: 200, height: 30)
        segmentView.selectedSegmentIndex = 0
        segmentView.layer.cornerRadius = 15
        segmentView.layer.borderWidth = 1;
        segmentView.tintColor = UIColor.init(red: 0.24, green: 0.59, blue: 1, alpha: 1)
    segmentView.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.black], for: .normal)
        
        segmentView.layer.borderColor = UIColor.init(red: 0.85, green: 0.85, blue: 0.85, alpha: 1).cgColor
        segmentView.layer.masksToBounds = true
        segmentView.addTarget(self, action: #selector(segmentClick(_segment:)), for: .valueChanged)
        return segmentView
    }()
    fileprivate lazy var scrollView : UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.backgroundColor = UIColor.white
        scrollView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        scrollView.delegate = self
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.isPagingEnabled = true
        scrollView.scrollsToTop = false
        scrollView.bounces = false
        scrollView.isScrollEnabled = false
        scrollView.contentSize = CGSize(width: 2*SCREEN_WIDTH, height: 0)
        return scrollView
    }()
    
    fileprivate lazy var tongjiLabel:UILabel = {
        let tap = UITapGestureRecognizer(target: self, action:#selector(rightClick))
        tap.numberOfTapsRequired = 1
        
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 40, height: 20))
        label.text = "统计"
        label.textAlignment = .center
        label.textColor = UIColor.black
        label.isUserInteractionEnabled = true
        label.isMultipleTouchEnabled = true
        label.addGestureRecognizer(tap)
        return label
    }()
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.addNotificationObserve()
        let img = UIColor.LightGreyBG.createImageWithColor()
        self.navigationController?.navigationBar.setBackgroundImage(img, for: .default)
        self.navigationController?.navigationBar.shadowImage = img
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.setBackgroundImage(UIColor.white.createImageWithColor(), for: .default)
        self.navigationController?.navigationBar.shadowImage = UIColor.gray.withAlphaComponent(0.5).createImageWithColor()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        SVProgressHUD.setDefaultMaskType(.clear)
        SVProgressHUD.setMinimumDismissTimeInterval(2)
        self.view.backgroundColor = UIColor.white
        self.navigationItem.titleView = segmentView
        self.view.addSubview(scrollView)
        self.setupTitleData(true)
        self.setupNavigationBar()
        self.setupChildController()
        self.addChildVcIntoScrollView()
        self.view.bringSubview(toFront: headerView)
        view.addSubview(dropDownMenu)
        view.bringSubview(toFront: dropDownMenu)
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(headerViewClick(tap:)))
        headerView.addGestureRecognizer(tap)
    }
    @objc func headerViewClick(tap:UITapGestureRecognizer) {
        if dropDownMenu.isShow! == false {
            self.projectName.text = "项目:" + (self.selectedProject?.ProjectName)! + " ▲"
            let point = CGPoint(x:SCREEN_WIDTH * 0.05,y: 40)
            dropDownMenu.popupMenu(orginPoint:point)
            dropDownMenu.didSelectIndex = { [weak self] (model:LCProjectListModel) in
                ProjectId = model.MarketSupplyBaseID!
                ProjectName = model.ProjectName!
                self?.projectName.text = "项目:" + (model.ProjectName)! + " ▼"
                self?.selectedProject = model
                self?.setupNotification()
                //self?.setupTitleData(false)
                /*self?.setupNotification()
                ProjectListNetWork.updateSeletedState(model.MarketSupplyBaseID!, completionHandler: { (response) in
                    if response{
                        self?.setupTitleData(true)
                        self.dropDownMenu.getProjectListData()
                    }
                })*/
            }
        }else{
            dropDownMenu.packUpMenu()
            self.projectName.text = "项目:" + (self.selectedProject?.ProjectName)! + " ▼"
        }
    }
    
    private func addNotificationObserve(){
        let noficationName = Notification.Name.init(LCNotificationMainRefresh)
        NotificationCenter.default.addObserver(self, selector: #selector(getDataRefresh(notification:)), name: noficationName, object: nil)
    }
    @objc private func getDataRefresh(notification:Notification){
        self.setupTitleData(true)
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    func setupNotification(){
        
        let center = NotificationCenter.default
        let notificationName = NSNotification.Name.init(LCMainProjectNotification)
        
        center.post(name: notificationName, object: nil, userInfo: ["project":self.selectedProject!])
    }
    
    private func setupTitleData(_ flag:Bool){
      //  WWProgressHUD.showWithStatus("正在载入数据...")
        //QWTextWithStatusHud("正在载入数据...", target: self.view)
        ProjectListNetWork.projectList(pageIndex: 1, pageSize: 25, keyword: "", isShowApplying: false) { (response) in
            if response.success {
                //QWHudDiss(self.view)
                self.itemArray = response.value!
                for index in self.itemArray{
                    print("\(index.ProjectRangeBean?.ElectricFenceList?.count)----\(index.ProjectRangeBean?.SignedPointList?.count)")
                }
                if self.itemArray.count > 0{
                let model : LCProjectListModel = self.itemArray[0]
                if model.IsAppSelected == true{
                    self.selectedProject = model
                    self.headerView.backgroundColor = UIColor.white
                    self.projectName.textColor = UIColor.init(red: 0.24, green: 0.59, blue: 1, alpha: 1)
                    self.projectName.text = "项目:" + model.ProjectName! + " ▼"
                    
                    //saveProjectId(model.MarketSupplyBaseID!)
                    ProjectId = model.MarketSupplyBaseID!
                    ProjectName = model.ProjectName!
                    self.getJGType(model)
                    //self.getTotal(model.MarketSupplyBaseID!)
                    if flag{
                        self.setupNotification()
                    }
                }else{
                    let alert1 = UIAlertController(title: "请选择一个项目", message: "如果需要创建新项目请前往PC端操作", preferredStyle: .alert)
                    
                    let cancel = UIAlertAction(title: "取消", style: .cancel) { (action) in
                        
                    }
                    cancel .setValue(UIColor.black, forKey: "titleTextColor")
                    let choose = UIAlertAction(title: "选择项目", style: .default) { (action) in
                        let project = LCProjectSelectViewController(nibName: "LCProjectSelectViewController", bundle: nil)
                        self.navigationController?.pushViewController(project, animated: true)
                    }
                    alert1.addAction(cancel)
                    alert1.addAction(choose)
                    self .present(alert1, animated: true) {
                        
                    }
                }
                    
                }else{
                    let alert = UIAlertController(title: "你当前还没有项目,请先前往PC端创建项目！", message: "", preferredStyle: .alert)
                    let cancel = UIAlertAction(title: "我知道了", style: .cancel, handler: { (action) in
                        
                        
                    })
                    alert.addAction(cancel)
                    self.present(alert, animated: true, completion: {
                        
                    })
                }
            }
            else {
                WWError(response.message)
            }
           // WWProgressHUD.dismiss()
        }
    }
    
    //请求计工方式
    /*func getTotal(_ projectid:String){
        var params:[String:Any]=["constructionProjectID":projectid ?? ""]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .KQTotal, params: &params, type: KaoQingTotal.self, success: { (bean) in
            guard var data = bean as? KaoQingTotal else{
                return
            }
            WorkType = data.Result?.WorkDayType ?? -1
        }) { (error) in
            
        }
        
    }*/
    
    //获取计工方式
    func getJGType(_ model:LCProjectListModel){
        var params:[String:Any] = ["contructionCompanyID":model.CompanyID ?? ""]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .JGFS, params: &params, type: Jgfs.self, success: { (bean,_) in
            guard let data = bean as? Jgfs else{
                return
            }
            WorkType = data.Result ?? -1
        }) { (error) in
            
        }
    }
    
    
    
    private func setupNavigationBar(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: "workerHead", target: self, action: #selector(tagClick))
        /*self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: "reply_n", target: self, action: #selector(messagePageClick))*/
        
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: tongjiLabel)
        
    }
    @objc fileprivate func messagePageClick(){
        
        
        
        
    }
    @objc fileprivate func tagClick() {
        self.mm_drawerController.toggle(MMDrawerSide.left, animated: true) { (completion) in
            
        }
    }
    
    @objc fileprivate func rightClick() {
        
        
        
        //print("rightclick")
        let tongjiVc = LCStatisticsController(nibName: "LCStatisticsController", bundle: nil)
        self.navigationController?.pushViewController(tongjiVc, animated: true)
    }
    
    
    private func setupChildController(){
        let scene = LCSceneViewController(nibName: "LCSceneViewController", bundle: nil)
        scene.refresh = { flag in
            self.setupTitleData(false)
        }
        self.addChildViewController(scene)
        let lcList = LCListViewController(nibName: "LCListViewController", bundle: nil)
        self.addChildViewController(lcList)
    }
    private func addChildVcIntoScrollView(){
        for i in 0..<2 {
            let childVc = self.childViewControllers[i]
            if childVc.isViewLoaded {
                return
            }
            let childVcView = childVc.view
            let scrollViewW = CGFloat(i) * SCREEN_WIDTH
            childVcView?.frame = CGRect(x: scrollViewW, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
            scrollView.addSubview(childVcView!)
        }
    }
}
extension LCMainViewController : UIScrollViewDelegate{
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//        let index = scrollView.contentOffset.x/scrollView.frame.size.width;
//        switch index {
//        case 0:
//            UIView.animate(withDuration: 0.2, animations: {
//                self.scrollView.contentOffset = CGPoint(x: 0, y: self.scrollView.contentOffset.y)
//            })
//        case 1 :
//            UIView.animate(withDuration: 0.2, animations: {
//                self.scrollView.contentOffset = CGPoint(x: SCREEN_WIDTH, y: self.scrollView.contentOffset.y)
//            })
//        default:
//            return
//        }
    }
}
// Mark:-点击事件
extension LCMainViewController{
    @objc fileprivate func segmentClick(_segment : UISegmentedControl){
        if _segment.selectedSegmentIndex == 0{
            UIView.animate(withDuration: 0, animations: {
                self.scrollView.contentOffset = CGPoint(x: 0, y: self.scrollView.contentOffset.y)
            })
        }else{
            UIView.animate(withDuration: 0, animations: {
                self.scrollView.contentOffset = CGPoint(x: SCREEN_WIDTH, y: self.scrollView.contentOffset.y)
            })
        }
    }
}




























